import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'

// 路由配置
const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: {
      title: '登录',
      requireAuth: false
    }
  },
  {
    path: '/',
    redirect: '/dashboard'
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('@/layout/Index.vue'),
    redirect: '/dashboard/home',
    meta: {
      title: '管理后台',
      requireAuth: true
    },
    children: [
      {
        path: 'home',
        name: 'Home',
        component: () => import('@/views/Dashboard/Home.vue'),
        meta: {
          title: '首页',
          icon: 'House'
        }
      },
      {
        path: 'business-types',
        name: 'BusinessTypes',
        component: () => import('@/views/BusinessTypes/Index.vue'),
        meta: {
          title: '业务类型管理',
          icon: 'Collection'
        }
      },
      {
        path: 'customers',
        name: 'Customers',
        component: () => import('@/views/Customers/Index.vue'),
        meta: {
          title: '客户管理',
          icon: 'User'
        }
      },
      {
        path: 'employees',
        name: 'Employees',
        component: () => import('@/views/Employees/Index.vue'),
        meta: {
          title: '员工管理',
          icon: 'Avatar'
        }
      },
      {
        path: 'businesses',
        name: 'Businesses',
        component: () => import('@/views/Businesses/Index.vue'),
        meta: {
          title: '业务管理',
          icon: 'Suitcase'
        }
      },
      {
        path: 'work-orders',
        name: 'WorkOrders',
        component: () => import('@/views/WorkOrders/Index.vue'),
        meta: {
          title: '工单管理',
          icon: 'Tickets'
        }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('@/views/Profile/Index.vue'),
        meta: {
          title: '个人中心',
          hidden: true
        }
      }
    ]
  },
  // 详情页面路由（使用相同的layout但不作为嵌套路由）
  {
    path: '/dashboard/customers/detail/:id',
    name: 'CustomerDetail',
    component: () => import('@/layout/Index.vue'),
    children: [
      {
        path: '',
        component: () => import('@/views/Customers/Detail.vue'),
        meta: {
          title: '客户详情',
          requireAuth: true
        }
      }
    ]
  },
  {
    path: '/dashboard/businesses/detail/:id',
    name: 'BusinessDetail',
    component: () => import('@/layout/Index.vue'),
    children: [
      {
        path: '',
        component: () => import('@/views/Businesses/Detail.vue'),
        meta: {
          title: '业务详情',
          requireAuth: true
        }
      }
    ]
  },
  {
    path: '/dashboard/work-orders/detail/:id',
    name: 'WorkOrderDetail',
    component: () => import('@/layout/Index.vue'),
    children: [
      {
        path: '',
        component: () => import('@/views/WorkOrders/Detail.vue'),
        meta: {
          title: '工单详情',
          requireAuth: true
        }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/Error/404.vue'),
    meta: {
      title: '页面不存在'
    }
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes
})

// 防止重复跳转登录页的标志
let isRedirectingToLogin = false

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - CRM管理系统`
  }
  
  // 如果不需要登录验证，直接放行
  if (to.meta.requireAuth === false) {
    // 如果已登录且访问登录页，重定向到首页
    if (to.name === 'Login' && userStore.token) {
      next('/dashboard')
      return
    }
    next()
    return
  }
  
  // 检查是否已登录
  if (!userStore.token) {
    if (!isRedirectingToLogin) {
      isRedirectingToLogin = true
      ElMessage.warning('请先登录')
      next('/login')
      setTimeout(() => {
        isRedirectingToLogin = false
      }, 1000)
    } else {
      next(false)
    }
    return
  }
  
  // 如果有token但没有用户信息，尝试获取用户信息
  if (!userStore.userInfo) {
    try {
      await userStore.getUserInfo()
      next()
    } catch (error) {
      console.error('获取用户信息失败:', error)
      // 避免重复调用logout和重复跳转
      if (!isRedirectingToLogin) {
        isRedirectingToLogin = true
        userStore.logout()
        next('/login')
        setTimeout(() => {
          isRedirectingToLogin = false
        }, 1000)
      } else {
        next(false)
      }
      return
    }
  } else {
    next()
  }
})

export default router 